package com.longqin.wechat.jwt;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import com.longqin.wechat.util.MyObjectUtil;


/**jwt拦截器
 *
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {

	 /**登录认证
     * 失败执行onAccessDenied方法
     * */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        //System.out.println(httpServletRequest.getRequestURI());
        String authorization = httpServletRequest.getHeader("public_token");
        if(MyObjectUtil.isNotNull(authorization)){
        	try {
        		JWTToken token = new JWTToken(authorization);
                getSubject(request, response).login(token); //提交给MyRealm,在方法doGetAuthenticationInfo中登录认证
                return true;
			} catch (Exception e) {
				return false;
			}	
        }
        return false;
    }

    /***
     * isAccessAllowed返回false执行
     * 返回认证失败信息
     * */
    @Override
	protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
    	HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setStatus(HttpServletResponse.SC_OK);
        httpResponse.setContentType("application/json; charset=utf-8");
        httpResponse.getWriter().write("{\"code\":403,\"msg\":\"Token认证失败\"}");
        return false;
	}


	/**
     * 对跨域提供支持
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

}
